//
//  DetailHvkViewController.m
//  ChatDemo-UI2.0
//
//  Created by zz on 16/5/25.
//  Copyright © 2016年 zz. All rights reserved.
//  作业详情

#import "DetailHvkViewController.h"
#import "SDPhotoBrowser.h"
#import "copyLabel.h"
#import "SYAnsToolbar.h"
#import "replayHNTableCell.h"
#import "MBProgressHUD.h"
#import "CustomAlert.h"
#import "SYMessageTool.h"

@interface DetailHvkViewController ()<SDPhotoBrowserDelegate,UIAlertViewDelegate,UITableViewDelegate,UITableViewDataSource,SYAnsToolbarDelegate,MBProgressHUDDelegate,UIGestureRecognizerDelegate,UIActionSheetDelegate,reloadDataDelegate>
@property(nonatomic,strong) UIView *topView; //顶部cell视图

@property(nonatomic,strong) UITableView *table;
@property(nonatomic,strong) NSMutableArray *commentsArr; //评论的数组

@property(nonatomic,strong) SYAnsToolbar *toobar;

@property(nonatomic,strong) UITapGestureRecognizer *reCallKeyboardTap;//回收键盘的手势

@property(nonatomic,strong) UITapGestureRecognizer *headerTap; //点击头像的手势

@end

@implementation DetailHvkViewController{
    
    int lasttype; //登录身份
    
    XZHeaderImageView *headView; //头像
    UILabel *nameLabel; //昵称
    UILabel *subLabel;//科目
    UILabel *classLabel; //班级
    UIButton *donBtn; //完成按钮
    UIView *lineView; //线
    UILabel *timeLabel; //时间
    
    UIScrollView *bottomScrollView;//底部的父视图
    UIView *imageBgView; //图片的背景view
    
    NSArray *imagesArr; //图片数组
    NSMutableArray *imageViews;
    
    CGFloat cellHeight; //第一个cell的高度
    
    NSString *toUserid; //回复的人的id
    
    ReplyModel *deleteModel; //将要删除的模型
    
}

-(UITapGestureRecognizer *)headerTap{
    
    if (_headerTap == nil) {
        
        _headerTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(headerTapAction:)];
    }
    
    return _headerTap;
}

-(UITapGestureRecognizer *)reCallKeyboardTap{
    
    if (_reCallKeyboardTap == nil) {
        
        _reCallKeyboardTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapTorecallKeyboard:)];
        _reCallKeyboardTap.delegate = self;
        
    }
    
    return _reCallKeyboardTap;
}

-(UIView *)topView{
    
    if (_topView == nil) {
        
        _topView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, VIEW_WIDTH, 63)];
        
        headView = [[XZHeaderImageView alloc] initWithFrame:CGRectMake(12, 12, 38, 38)];
        //headView.layer.cornerRadius = 26;
        //headView.clipsToBounds = YES;
        headView.namelabel.font = [UIFont systemFontOfSize:14];
        [headView updateViewWithLogoStr:_model.logo];
        
        NSString *str = _model.username;
        if (str && str.length > 2) {
            str = [str substringFromIndex:str.length - 2];
        }
        headView.flag = _model.logotype == 1?YES:NO;
        headView.namelabel.text = str;
        [_topView addSubview:headView];
        
        CGFloat headX = CGRectGetMaxX(headView.frame)+15;
        nameLabel = [[UILabel alloc] initWithFrame:CGRectMake(headX, 14, 200, 14)];
        nameLabel.font = [UIFont boldSystemFontOfSize:15];
        nameLabel.textColor = RGBACOLOR(59, 59, 59, 1);
        nameLabel.text = _model.username;
        [_topView addSubview:nameLabel];
        
        subLabel = [[UILabel alloc] initWithFrame:CGRectMake(headX, CGRectGetMaxY(nameLabel.frame) + 8, 200, 13)];
        subLabel.font = [UIFont systemFontOfSize:14];
        subLabel.textColor = RGBACOLOR(151, 151, 151, 1);
        //subLabel.text = [NSString stringWithFormat:@"学科  :  %@",_model.coursename];;
        subLabel.text = [NSString stringWithFormat:@"%@   %@",_model.classname,_model.coursename.length > 0 ? _model.coursename : @""];
        [_topView addSubview:subLabel];
        
        //classLabel = [[UILabel alloc] initWithFrame:CGRectMake(headX, CGRectGetMaxY(subLabel.frame)+14, 200, 14)];
        //classLabel.font = [UIFont systemFontOfSize:14];
        //classLabel.textColor = RGBACOLOR(59, 59, 59, 1);
        //classLabel.text = [NSString stringWithFormat:@"班级  :  %@",_model.classname];
        //[_topView addSubview:classLabel];
        
        //时间label
        timeLabel = [[UILabel alloc] initWithFrame:CGRectMake(SCREENWIDTH - 12 - 150, 12, 150, 10)];
        timeLabel.font = [UIFont systemFontOfSize:12];
        timeLabel.textColor = RGBACOLOR(151, 151, 151, 1);
        timeLabel.textAlignment = NSTextAlignmentRight;
        if (_model.jointime!=nil) {
            
            NSString *time = [Utils getDataStringWithoutSecondString:_model.jointime];
            
            timeLabel.text = time;
        }

        [_topView addSubview:timeLabel];
        
        /*完成按钮改了位置*/
        ////完成按钮
        //donBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        //donBtn.frame = CGRectMake(SCREENWIDTH - 72, 51, 60, 30);
        //donBtn.layer.cornerRadius = 5;
        //donBtn.titleLabel.font = [UIFont systemFontOfSize:14];
        //donBtn.backgroundColor = RGBACOLOR(56, 173, 255, 1);
        
        //NSString *btnTitleStr;
        //if (_model.isfinish == 1) {
            //btnTitleStr = @"已完成";
            //[donBtn setBackgroundColor:[UIColor lightGrayColor]];
            //donBtn.enabled = NO;
            
        //}else if (_model.isfinish == 0){
            //btnTitleStr = @"完成";
        //}
        
        //if (_model.type == 2) {  //如果是通知的话，就隐藏完成按钮
            //donBtn.hidden = YES;
        //}else{
            
            
            //if (lasttype == 1) {
                //donBtn.hidden = YES;
            //}else if (lasttype == 2){
                //donBtn.hidden = NO;
            //}
            
        //}
        
        //[donBtn setTitle:btnTitleStr forState:UIControlStateNormal];
        //[donBtn setTitleColor:RGBACOLOR(255, 255, 255, 1) forState:UIControlStateNormal];
        //[donBtn addTarget:self action:@selector(donBtnClick:) forControlEvents:UIControlEventTouchUpInside];
        
        
        //[_topView addSubview:donBtn];
        
        //线
        lineView = [[UIView alloc] initWithFrame:CGRectMake(0, 62.5, SCREENWIDTH, 0.5)];
        lineView.backgroundColor = RGBACOLOR(199, 199, 204, 1);
        [_topView addSubview:lineView];

    }
    
    return _topView;
}

-(NSMutableArray *)commentsArr{
    
    if (!_commentsArr) {
        
        _commentsArr = [NSMutableArray array];
    }
    
    return _commentsArr;
}

-(SYAnsToolbar *)toobar{
    
    if (_toobar == nil) {
        
        _toobar = [[SYAnsToolbar alloc] initWithFrame:CGRectMake(0, CGRectGetMaxY(self.table.frame), self.view.frame.size.width, [SYAnsToolbar defaultHeightWithCanAnswer:YES])];
        _toobar.backgroundColor = [UIColor whiteColor];
        _toobar.inputTextView.placeHolder = @"请在此输入您的评论";
        _toobar.delegate = self;
    }
    
    return _toobar;
}


-(UITableView *)table{
    
    if (_table == nil) {
        
        _table = [[UITableView alloc] initWithFrame:CGRectMake(0,SafeAreaTopHeight, VIEW_WIDTH, VIEW_HEIGHT - 64 - 50) style:UITableViewStylePlain];
        _table.delegate = self;
        _table.dataSource = self;
        
        _table.tableFooterView = [[UIView alloc] init];
        _table.separatorStyle = UITableViewCellSeparatorStyleNone;
        _table.backgroundColor = TABLEHEADERBGCOLOR;
        
        _table.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
           
            [self loadReplayListData];
        }];

    }
    
    return _table;
}

-(void)initArr{

    imageViews = [NSMutableArray array];

}

- (id)init
{
    self = [super init];
    if (self) {
        self.hidesBottomBarWhenPushed = YES;
    }
    return self;
}
- (void)viewWillAppear:(BOOL)animated {
    
    [super viewWillAppear:YES];
    
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self.view setBackgroundColor:[UIColor whiteColor]];
    
    //判断身份,如果是老师身份的话，需要隐藏完成按钮
    lasttype = [SYAccountTool ShareAccount].account.lasttype;
    
    if (self.model) {
       
        [self initArr];
        
        [self configureNav];
        
        [self configureUI];
        
        //标记已读
        if (lasttype == 2) {
            
            [self getDetailData];
           
        }
        
        //加载回复列表
        [self loadReplayListData];
       
    }else if (self.infoID){
        
        [self getInfoModel];
    }
   
   if (lasttype == 2) {
         
       [self changeReadState];
      
   }
   
    
}

- (void)getInfoModel {
    
    NSMutableDictionary *param = [NSMutableDictionary dictionary];
    
    [param setObject:self.infoID forKey:@"infoid"];
    
    [param setObject:USERID forKey:@"userid"];
    
    if (lasttype == 1) {
        [param setObject:@"api_info_get" forKey:@"Method"];
        [param setObject:@"0" forKey:@"studentid"];
        
    }else {
        
        [param setObject:@"api_info_getbystudent" forKey:@"Method"];
        
    }
    
    [Utils get:nil parameters:param success:^(NSInteger recode, id jsonObject) {
        
        
        NSDictionary *dic = [[jsonObject objectForKey:@"re_data"] firstObject];
        
        if (dic) {
            
            self.model = [homework mj_objectWithKeyValues:dic];
            [self initArr];
            
            [self configureNav];
            
            [self configureUI];
            
            //标记已读
            if (self->lasttype == 2) {
                
                [self getDetailData];
            }
            
            //加载回复列表
            [self loadReplayListData];

        }else{
            
            [Utils alertViewWithMessage:@"此版本暂不支持"];
            return;
        }
        
    } failure:^(NSInteger recode, NSError *error) {
        
    }];
}

-(void)configureNav{
   
   
    if (lasttype ==1) {
        
        if (_model.type ==2) {
            
            self.navBar.nav_titleLabel.text= @"通知详情";
        }else
        {
            self.navBar.nav_titleLabel.text= @"作业详情";
        }
        
    }else
    {
        if (_model.type ==2) {
            
            if ([_fromVC isEqualToString:@"zhuye"]) {
                
                self.navBar.nav_titleLabel.text= @"通知详情";
                
            }else
            {
            
                self.navBar.nav_titleLabel.text= [NSString stringWithFormat:@"%@的通知",_model.studentname];
            }
            
        }else
        {
            if ([_fromVC isEqualToString:@"zhuye"]) {
                
                self.navBar.nav_titleLabel.text= @"作业详情";
                
            }else
            {
                
                self.navBar.nav_titleLabel.text= [NSString stringWithFormat:@"%@的作业",_model.studentname];
                
            }
        }
    }
    
    
    UIBarButtonItem *backItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"back"] style:UIBarButtonItemStyleDone target:self action:@selector(back)];
    self.navigationItem.leftBarButtonItem = backItem;

    self.edgesForExtendedLayout = UIRectEdgeNone;
    
    self.view.backgroundColor = [UIColor whiteColor];
}

-(void)back{
    
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

-(void)configureUI{

    //topViwe = [[UIView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, 90)];
    //[self.view addSubview:topViwe];
    
    
    [self.view addSubview:self.table];
    
    [self.view addSubview:self.toobar];
    
    
    /*添加回收键盘的手势*/
    [self.view addGestureRecognizer:self.reCallKeyboardTap];
    
    [self setupScrollView];
    
}

-(void)setupScrollView{
    
    //bottomScrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 90, SCREENWIDTH, VIEW_HEIGHT - 90 - 64)];
    //[self.view addSubview:bottomScrollView];
    bottomScrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 0, VIEW_WIDTH, 300)];
    
    UILabel *titleL = [[UILabel alloc] initWithFrame:CGRectMake(12, 20, 200, 17)];
    
    //标题内容
    UILabel *titleLabel;
    
    if (_model.type == 2) {
        titleL.text = @"通知内容:";
        
        titleLabel = [[UILabel alloc] init];
        titleLabel.font = [UIFont boldSystemFontOfSize:16];
        titleLabel.textColor = RGBACOLOR(59, 59, 59, 1);
        titleLabel.text = [NSString stringWithFormat:@"%@",_model.title];
        titleLabel.numberOfLines = 2;
        [bottomScrollView addSubview:titleLabel];
        
        CGFloat height = [_model.title boundingRectWithSize:CGSizeMake(SCREENWIDTH - 24, 1000) options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName: [UIFont systemFontOfSize:16]} context:nil].size.height;
        
        titleLabel.frame = CGRectMake(12, /*CGRectGetMaxY(titleL.frame)+20*/12, SCREENWIDTH - 24, height);
        
    }else if (_model.type == 3){
        titleL.text = @"作业内容:";
    }
    
    titleL.font = [UIFont systemFontOfSize:17];
    //[bottomScrollView addSubview:titleL];
    
    CGFloat w = VIEW_WIDTH - 24;
    NSMutableParagraphStyle *style = [[NSMutableParagraphStyle alloc] init];

    [style setLineSpacing:2];
    [style setFirstLineHeadIndent:30];
    //NSString *str =[NSString stringWithFormat:@"         %@",_model.scontent];
    NSString *str = _model.scontent;
    CGFloat conutH = [str boundingRectWithSize:CGSizeMake(w, 1000) options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName: [UIFont systemFontOfSize:15],NSParagraphStyleAttributeName:style} context:nil].size.height;
    
    copyLabel *contentL = [[copyLabel alloc] init];
    
    if (_model.type == 2) {  //通知
        contentL.frame = CGRectMake(12, CGRectGetMaxY(titleLabel.frame)+12, w, conutH);
    }else if (_model.type == 3){  //作业
        contentL.frame = CGRectMake(12, 12/*CGRectGetMaxY(titleL.frame)+20*/, w, conutH);
    }
    
    contentL.font = [UIFont systemFontOfSize:15];
    
    if (_model.scontent > 0) {
        
        //NSString *contentStr = [NSString stringWithFormat:@"         %@",_model.scontent];
        
        NSMutableAttributedString *str = [[NSMutableAttributedString alloc] initWithString:_model.scontent];
        NSMutableParagraphStyle *style = [[NSMutableParagraphStyle alloc] init];
        [style setLineSpacing:2];
        [style setFirstLineHeadIndent:30];
        [str addAttribute:NSParagraphStyleAttributeName value:style range:NSMakeRange(0, _model.scontent.length)];
        contentL.attributedText = str;
        //contentL.text =[NSString stringWithFormat:@"         %@",_model.scontent] ;
    }else{
        
        if (_model.type == 2) {
            
            contentL.text = @"         通知内容,请点击查看图片信息";
        }else if (_model.type == 3){
            contentL.text = @"         作业内容,请点击查看图片信息";
        }
    }
    
    contentL.numberOfLines = 0;
    contentL.textColor = RGBACOLOR(59, 59, 59, 1);
    [bottomScrollView addSubview:contentL];
    
    
    //计算图片的布局
    NSString *fieldStr = _model.fileid;
    
    if (fieldStr.length > 0) { //有图片
        imagesArr = [fieldStr componentsSeparatedByString:@","];
        
        int count = (int)imagesArr.count;
        CGFloat x,y,w,h,s,height;
        s = 9;
        w = (VIEW_WIDTH - 24 - 18) / 3;
        h = w;
        
        height = ((count - 1) / 3) * (s + h) + h;
        
        imageBgView = [[UIView alloc] initWithFrame:CGRectMake(12, CGRectGetMaxY(contentL.frame)+12, VIEW_WIDTH - 24, height)];
        imageBgView.backgroundColor = [UIColor whiteColor];
        [bottomScrollView addSubview:imageBgView];
        
        //scrollView的滚动高度
        CGFloat contentHeight = CGRectGetMaxY(imageBgView.frame)  + 40 + s;
        
        //改变scrollview的高度
        CGRect rect = bottomScrollView.frame;
        rect.size.height = contentHeight;
        
        //赋值给cell的高度
        cellHeight = contentHeight;
        bottomScrollView.frame = rect;
        //bottomScrollView.contentSize = CGSizeMake(VIEW_WIDTH, contentHeight);
        
        for (int i = 0; i < count; i++) {
            
            NSString *losoStr = imagesArr[i];
            losoStr = [PICPERFIXURL stringByAppendingString:losoStr];
            
            x = (i % 3) * (s + w);
            y = (i / 3) * (s + h);
            UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(x, y, w, h)];
            imageView.contentMode = UIViewContentModeScaleAspectFill;
            imageView.clipsToBounds = YES;
            imageView.tag = i;
            imageView.userInteractionEnabled = YES;
            [imageView sd_setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@&s=%d",losoStr,ImageWidht]] placeholderImage:[UIImage imageNamed:@"emptyPic"]];
            
            //添加手势
            UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapAction:)];
            [imageView addGestureRecognizer:tap];
            [imageViews addObject:imageView];
            
            [imageBgView addSubview:imageView];
        }
        
    }else{  //没有图片
    
        cellHeight = CGRectGetMaxY(contentL.frame) + 10 + 40;
    }
    
    //作业详情的完成按钮
    if (lasttype == 2 && _model.type == 3) {
        
        //完成按钮
        donBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        donBtn.frame = CGRectMake(SCREENWIDTH - 73 - 12, cellHeight - 40, 73, 30);
        donBtn.layer.cornerRadius = 8;
        donBtn.titleLabel.font = [UIFont systemFontOfSize:14];
        donBtn.backgroundColor = RGBACOLOR(56, 173, 255, 1);
        
        NSString *btnTitleStr;
        if (_model.isfinish == 1) {
            btnTitleStr = @"已完成";
            //[donBtn setBackgroundColor:[UIColor lightGrayColor]];
            [donBtn setTitleColor: RGBCOLOR(221, 221, 221) forState:UIControlStateNormal];
            
            donBtn.layer.borderColor = RGBCOLOR(221, 221, 221).CGColor;
            
            donBtn.enabled = NO;
            
        }else{
            
            btnTitleStr = @"确认完成";
            [donBtn setTitleColor: RGBCOLOR(57, 173, 255) forState:UIControlStateNormal];
            donBtn.layer.borderColor = RGBCOLOR(57, 173, 255).CGColor;
            
        }
        
        //if (_model.type == 2) {  //如果是通知的话，就隐藏完成按钮
        //donBtn.hidden = YES;
        //}else{
        
        
        ////if (lasttype == 1) {
        ////donBtn.hidden = YES;
        ////}else if (lasttype == 2){
        ////donBtn.hidden = NO;
        ////}
        
        //}
        
        [donBtn setTitle:btnTitleStr forState:UIControlStateNormal];
        //[donBtn setTitleColor:RGBACOLOR(255, 255, 255, 1) forState:UIControlStateNormal];
        [donBtn addTarget:self action:@selector(donBtnClick:) forControlEvents:UIControlEventTouchUpInside];
        donBtn.layer.borderWidth = 1;
        [donBtn setBackgroundColor:[UIColor whiteColor]];
        
        [bottomScrollView addSubview:donBtn];
        
    }

}

-(void)tapAction:(UIGestureRecognizer *)gesture{
    
    SDPhotoBrowser *browser = [[SDPhotoBrowser alloc] init];
    browser.sourceImagesContainerView = imageBgView;
    browser.imageCount = imagesArr.count;
    
    browser.currentImageIndex = (int)gesture.view.tag;
    browser.delegate = self;
    [browser show];
}

-(UIImage *)photoBrowser:(SDPhotoBrowser *)browser placeholderImageForIndex:(NSInteger)index flag:(NSString *)flagStr{
    
    UIImageView *imageView = imageViews[index];
    return imageView.image;
}


//-(NSURL *)photoBrowser:(SDPhotoBrowser *)browser highQualityImageURLForIndex:(NSInteger)index{
//    
//    NSString *urlStr = imagesArr[index];
//    
//    urlStr = [PICPERFIXURL stringByAppendingString:urlStr];
//    return [NSURL URLWithString:urlStr];
//}
//-(UIImage *)photoBrowser:(SDPhotoBrowser *)browser placeholderImageForIndex:(NSInteger)index flag:(NSString *)flagStr{
//    
//    NSString *str = imagesArr[index];
//    NSString *logoStr;
//    if ([flagStr isEqualToString:@"1"]) {
//        logoStr = [PICPERFIXURL stringByAppendingString:str];
//    }else
//    {
//        logoStr = [PICPERFIXURL stringByAppendingString:str];
//        logoStr=[NSString stringWithFormat:@"%@&s=%d",logoStr,ImageWidht];
//    }
//    
//    UIImageView *imageView = [[UIImageView alloc] init];
//    
//    __block UIImage *_image;
//    [imageView sd_setImageWithURL:[NSURL URLWithString:logoStr] completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) {
//        
//        _image = image;
//    }];
//    return _image;
//}

- (NSURL *)photoBrowser:(SDPhotoBrowser *)browser highQualityImageURLForIndex:(NSInteger)index flag:(NSString *)flagStr{
    
    NSString *str = imagesArr[index];
    NSString *logoStr;
    if ([flagStr isEqualToString:@"1"]) {
        logoStr = [PICPERFIXURL stringByAppendingString:str];
    }else
    {
        logoStr = [PICPERFIXURL stringByAppendingString:str];
        logoStr=[NSString stringWithFormat:@"%@&s=%d",logoStr,ImageWidht];
    }
    
    
    NSURL *url = [NSURL URLWithString:logoStr];
    return url;
}


#pragma mark -完成按钮点击事件
-(void)donBtnClick:(UIButton *)sender{
    
    
    UIAlertView *alert=[[UIAlertView alloc]initWithTitle:@"提示" message:@"您确定完成此项作业了吗？" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil];
    alert.tag=101;
    [alert show];

}

-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
    
    if (alertView.tag==101) {

    if (buttonIndex==1) {
        
        NSMutableDictionary * param = [[NSMutableDictionary alloc] initWithCapacity:0];
        [param setObject:@"api_info_isfinish" forKey:@"method"];
        [param setObject: _model.infoid forKey:@"infoid"];
        [param setObject:USERID forKey:@"userid"];
        [param setObject:@"1" forKey:@"isfinish"];
        
        if (_model.studentid) {
            
            [param setObject:_model.studentid forKey:@"studentid"];
        }
        
//        else{
//            
//           NSString *studentid = [[NSUserDefaults standardUserDefaults] objectForKey:@"studentID"];
//            
//            if (studentid) {
//                
//                [param setObject:studentid forKey:@"studentid"];
//            }
//        }
        
        [param setObject: _model.classid forKey:@"classid"];
        
        [Utils noHUD_get:nil parameters:param success:^(NSInteger recode, id resposeJson){
            
            self->finshDIc = resposeJson;
            NSInteger re_code = [[resposeJson objectForKey:@"re_code"] integerValue];
            
            if (re_code == 0) {
                
                
                self-> donBtn.layer.cornerRadius = 8;
                self->donBtn.titleLabel.font = [UIFont systemFontOfSize:14];
                self-> donBtn.backgroundColor = [UIColor whiteColor];
                [self->donBtn setTitleColor: RGBCOLOR(221, 221, 221) forState:UIControlStateNormal];
                
                self->donBtn.layer.borderColor = RGBCOLOR(221, 221, 221).CGColor;
                
                self->donBtn.enabled = NO;

                
                [self->donBtn setTitle:@"已完成" forState:UIControlStateNormal];
//                [self->donBtn setBackgroundColor:[UIColor ]];
//                self->donBtn.enabled = NO;
                
                self->_model.isfinish = 1;
                
                [self->_delegate updateModel:self->_model andIndex:self->_index];
                
                UIAlertView *alert=[[UIAlertView alloc]initWithTitle:nil message:[self->finshDIc objectForKey:@"re_info"] delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
                alert.tag=102;
                [alert show];
            }
            
//            [self.navigationController popViewControllerAnimated:YES];
            
           
            
            
        } failure:^(NSInteger recode, NSError * error){
            
            if (error.code == -1009) {
                
                [self showHint:@"网络异常,请稍后再试!"];
            }
        }];
        
        
       }
        
    }else if (alertView.tag==102)
    {
        id num=[self->finshDIc objectForKey:@"integalnum"];
        if (![num isKindOfClass:[NSNull class]]) {
            NSString *n=num;
            if ([n intValue]>0) {
                CustomAlert *alert=[CustomAlert ShareCustomAlert];
                [alert showAlertTaskString:@"做作业" andNum:[n intValue]];
                //                    [self->_isfinshdelegate showYunDouAlert:@"做作业" andNum:[n intValue]];
                
            }
        }

    }

}

- (void)getDetailData
{
        NSMutableDictionary *param = [NSMutableDictionary dictionary];
        [param setObject:_model.infoid forKey:@"infoid"];
        [param setObject:USERID forKey:@"userid"];
        [param setObject:_model.studentid forKey:@"studentid"];
        [param setObject:_model.classid forKey:@"classid"];
        [param setObject:@"api_info_getbystudent" forKey:@"Method"];

        [Utils get:nil parameters:param success:^(NSInteger recode, id jsonObject) {
        
            self->readDic=jsonObject;
            
            NSInteger num = [[jsonObject objectForKey:@"re_code"] integerValue];
            if (num == 0) {
                //代理标记已读
                self->_model.isread = [NSString stringWithFormat:@"%d",1];
                [self->_delegate updateModel:self->_model andIndex:self->_index];
                
                
//                id num=[self->readDic objectForKey:@"integalnum"];
//                if (![num isKindOfClass:[NSNull class]]) {
//                    NSString *n=num;
//                    if ([n intValue]>0) {
//
//                        CustomAlert *alert=[CustomAlert ShareCustomAlert];
//                        [alert showAlertTaskString:@"阅读作业" andNum:[n intValue]];
//                    }
//
//                }
               
            }
        
         } failure:^(NSInteger recode, NSError *error) {
        
    }];
}
- (void)changeReadState{

      SY_Activity_Model * model = [[SY_Activity_Model alloc]init];
      model.readState = 1;
   
      if (self.model) {
      
       model.infoid = self.model.infoid;
       
      }else{
         
         model.infoid = _infoID;
      }
   
   [SYMessageTool updataMessageModel:model];

}
#pragma mark -标记已读
-(void)isRead{
    
    NSMutableDictionary *param = [NSMutableDictionary dictionary];
    
    [param setObject:@"api_info_isread" forKey:@"method"];
    [param setObject:_model.infoid forKey:@"infoid"];
    [param setObject:USERID forKey:@"userid"];
    [param setObject:_model.studentid forKey:@"studentid"];
    [param setObject:_model.classid forKey:@"classid"];
    
    [Utils get:nil parameters:param success:^(NSInteger recode, id jsonObject) {
    
        self->readDic=jsonObject;
        
        NSInteger num = [[jsonObject objectForKey:@"re_code"] integerValue];
        if (num == 0) {
            //代理标记已读
            self->_model.isread = [NSString stringWithFormat:@"%d",1];
            [self->_delegate updateModel:self->_model andIndex:self->_index];
       
            
//            id num=[self->readDic objectForKey:@"integalnum"];
//            if (![num isKindOfClass:[NSNull class]]) {
//                NSString *n=num;
//                if ([n intValue]>0) {
//                    CustomAlert *alert=[CustomAlert ShareCustomAlert];
//                    [alert showAlertTaskString:@"阅读作业" andNum:[n intValue]];
//                }
//
//            }

        }
        
    } failure:^(NSInteger recode, NSError *error) {
        
    }];
}

#pragma mark -UITableViewDatasource
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    
    return 3;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    if (section == 0 || section == 1) {
        
        return 1;
    }else{
        
        return self.commentsArr.count;
    }
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    if (indexPath.section == 0) {
        
        UITableViewCell *cell = [[UITableViewCell alloc] init];
        [cell.contentView addSubview:self.topView];
        
        return cell;
    }else if (indexPath.section == 1){
        
        UITableViewCell *cell = [[UITableViewCell alloc] init];
        [cell.contentView addSubview:bottomScrollView];
        return cell;
        
    }else{
     
        static NSString *newid = @"cellid";
        replayHNTableCell *cell = [tableView dequeueReusableCellWithIdentifier:newid];
        if (cell == nil) {
            
           cell = [[replayHNTableCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:newid];
        }
        
        ReplyModel *model = [self.commentsArr objectAtIndex:indexPath.row];
        
        [cell updateCellWithModel:model];
        
        UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(headerTapAction:)];
        
        cell.headView.userInteractionEnabled = YES;
        cell.headView.tag = indexPath.row;
        [cell.headView addGestureRecognizer:tap];
        
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        
        return cell;
    }
    
}

#pragma mark -UITableViewDelegate
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    if (indexPath.section == 0) {
        
        return 63;
        
    }else if (indexPath.section == 1) {
        
        if (lasttype == 2 && _model.type == 3) {
            
            return cellHeight;
        }
        
        return cellHeight;
        
    }else{
        
        ReplyModel *model = [_commentsArr objectAtIndex:indexPath.row];
        
        return model.cellHeight;
    }
}

-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    
    
    //有评论时候的view
    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, VIEW_WIDTH, 25)];
    view.backgroundColor = [UIColor whiteColor];
    
    UIView *line1 = [[UIView alloc] initWithFrame:CGRectMake(0, 0, VIEW_WIDTH, 0.5)];
    line1.backgroundColor = LINECOLOR;
    [view addSubview:line1];
    
    UIView *middView = [[UIView alloc] initWithFrame:CGRectMake(0, 0.5, VIEW_WIDTH, 9)];
    middView.backgroundColor = TABLEHEADERBGCOLOR;
    [view addSubview:middView];
    
    UIView *line2 = [[UIView alloc] initWithFrame:CGRectMake(0, 9.5, VIEW_WIDTH, 0.5)];
    line2.backgroundColor = LINECOLOR;
    [view addSubview:line2];
    
    UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
    [btn setImage:[UIImage imageNamed:@"pinglun_huifu_"] forState:UIControlStateNormal];
    NSString *btnTitle = [NSString stringWithFormat:@"共有%lu条回复",(unsigned long)_commentsArr.count];
    [btn setBackgroundColor:[UIColor whiteColor]];
    [btn setTitle:btnTitle forState:UIControlStateNormal];
    [btn setTitleEdgeInsets:UIEdgeInsetsMake(0, 4, 0, 0)];
    btn.titleLabel.font = [UIFont systemFontOfSize:13];
    [btn setTitleColor:RGBCOLOR(151, 151, 151) forState:UIControlStateNormal];
    btn.frame = CGRectMake(8, CGRectGetMaxY(line2.frame) + 12 , 100, 13);
    [view addSubview:btn];
    
    //没有评论时候的veiw
    UIView *view2 = [[UIView alloc] initWithFrame:CGRectMake(0, 0, VIEW_WIDTH, 37)];
    
    UILabel *label2 = [[UILabel alloc] initWithFrame:CGRectMake(12, 10, 200, 26)];
    label2.font = [UIFont systemFontOfSize:14];
    label2.textColor = RGBCOLOR(151, 151, 151);
    label2.text = @"暂无评论";
    [view2 addSubview:label2];
    
    [view2 addSubview:line1];
    
    if (section == 2) {
        
        if (_commentsArr.count > 0) {
            
            return view;
        }else{
            
            return view2;
        }
        
    }else{
        
        return nil;
    }
    
}

-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    
    if (section == 2) {
        return 37;
    }
    return 0;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    if (indexPath.section == 2) {
        
        ReplyModel *model = [self.commentsArr objectAtIndex:indexPath.row];
        
        NSString *idStr = [NSString stringWithFormat:@"%ld",(long)model.userid];
        
        if ([idStr isEqualToString:USERID]) {
            
            [self showDeleteAlert];
            
            deleteModel = model;
            
        }else{
        
            NSString *pldStr = [NSString stringWithFormat:@"回复：@%@",model.username];
            self.toobar.inputTextView.placeHolder = pldStr;
            
            toUserid = [NSString stringWithFormat:@"%ld",(long)model.userid];
            
            [self.toobar.inputTextView becomeFirstResponder];
        }
    }
    
}

#pragma mark -点击动态，自己发的删除
-(void)showDeleteAlert{
    
    UIActionSheet *sheet = [[UIActionSheet alloc] initWithTitle:nil delegate:self cancelButtonTitle:@"取消" destructiveButtonTitle:@"删除" otherButtonTitles:nil];
    [sheet showInView:self.view];
}

-(void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex{
    
    if (buttonIndex == 1) return;
    
    BaseModel *param = [BaseModel param];
    param.method = @"api_info_replydel";
    param.replyid = [NSString stringWithFormat:@"%ld",(long)deleteModel.replyid];;
    
    [Utils get:nil parameters:param.mj_keyValues success:^(NSInteger recode, id jsonObject) {
        
        [self ->_commentsArr removeObject:self->deleteModel];
        self->deleteModel = nil;
        [self.table reloadData];
        
        UIWindow *window = [UIApplication sharedApplication].keyWindow;
        
        MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:window animated:YES];
        hud.customView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"chatBar_face"]];
        hud.mode = MBProgressHUDModeCustomView;
        hud.delegate = self;
        hud.labelFont = [UIFont systemFontOfSize:15];
        hud.labelText = @"删除成功";
        [hud show:YES];
        [hud hide:YES afterDelay:2];

        
    } failure:^(NSInteger recode, NSError *error) {
        
        
    }];
    
}

#pragma mark -回收键盘的手势

-(BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldReceiveTouch:(UITouch *)touch{
    
    if (![gestureRecognizer isEqual:_reCallKeyboardTap]) {

        return YES;
    }
    
    if ([self.toobar.inputTextView isFirstResponder]) {
        return YES;
    }
    
    return NO;
}

-(void)tapTorecallKeyboard:(UIGestureRecognizer *)gegz{
    
    [self.toobar endEditing:YES];
}

#pragma mark -toolBarDelegate
-(void)didSendText:(NSString *)text{
    
     self.toobar.sendButton.userInteractionEnabled=NO;
    
    if ([[self.toobar.inputTextView.text stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]] length]==0) {
        
        [Utils alertViewWithMessage:@"请输入您的评论"];
        
        return;
    }
    
    if (self.toobar.inputTextView.text.length > 200) {
        
        [Utils alertViewWithMessage:@"请将您的内容限制在200字以内"];

        return;
    }
    
    BaseModel *param = [BaseModel param];
    
    param.method = @"api_info_replyadd";
    param.infoid = _model.infoid;
    param.scontent = self.toobar.inputTextView.text;
    param.touserid = toUserid;
    
    self.toobar.inputTextView.text = @"";
    
    [Utils noIndiGet:nil parameters:param.mj_keyValues success:^(NSInteger recode, id jsonObject) {
        
        [self.toobar endEditing:YES];
        //改变原来回复的人
        self->toUserid = nil;
        self.toobar.inputTextView.placeHolder = @"请在此输入您的评论";

        NSDictionary *dic = [[jsonObject objectForKey:@"re_data"] objectAtIndex:0];
        ReplyModel *model = [ReplyModel mj_objectWithKeyValues:dic];
        [self ->_commentsArr insertObject:model atIndex:0];
        NSIndexPath *indexPath = [NSIndexPath indexPathForRow:0 inSection:2];
        [self.table reloadData];
        [self.table scrollToRowAtIndexPath:indexPath atScrollPosition:UITableViewScrollPositionTop animated:YES];
        
        self.toobar.inputTextView.text = @"";
        UIWindow *window = [UIApplication sharedApplication].keyWindow;
        
        MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:window animated:YES];
        hud.customView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"chatBar_face"]];

        hud.mode = MBProgressHUDModeCustomView;
        hud.delegate = self;
        hud.labelFont = [UIFont systemFontOfSize:15];
        hud.labelText = @"发送成功";
        [hud show:YES];
        [hud hide:YES afterDelay:2];


    } failure:^(NSInteger recode, NSError *error) {
        
    }];
}

#pragma mark -加载回复列表
-(void)loadReplayListData{
    
    BaseModel *param = [BaseModel param];
    
    param.pageno = @"1";
    param.pagesize = @"1000";
    param.infoid = _model.infoid;
    param.method = @"api_info_replylist";
    
    [Utils get:nil parameters:param.mj_keyValues success:^(NSInteger recode, id jsonObject) {
        
        NSArray *arr = [jsonObject objectForKey:@"re_data"];
        
        [SYClassesTool saveCacheDataWithNSArr:arr withInfoID:self->_model.infoid];
        
        [SYClassesTool getCacheDataFromInfoID:self->_model.infoid];
        
        NSArray *modelArr = [ReplyModel mj_objectArrayWithKeyValuesArray:arr];
        
        NSIndexSet *indexSet = [NSIndexSet indexSetWithIndexesInRange:NSMakeRange(0, modelArr.count)];
        if (self ->_commentsArr.count >= modelArr.count) {
            
            [self ->_commentsArr replaceObjectsAtIndexes:indexSet withObjects:modelArr];
        }else{
            
            [self ->_commentsArr addObjectsFromArray:modelArr];
        }
        
        [self.table.mj_header endRefreshing];
        
        [self.table reloadData];
        
    } failure:^(NSInteger recode, NSError *error) {
        
        
        
    }];
}

#pragma mark -MBProgerssHudDelegate
-(void)hudWasHidden:(MBProgressHUD *)hud{
    
    [hud removeFromSuperview];
    hud = nil;
}

#pragma mark -头像点击事件
-(void)headerTapAction:(UIGestureRecognizer *)geza{
    
//    UIView *view = geza.view;
//
//    ReplyModel *model = [self.commentsArr objectAtIndex:view.tag];
//
//    UserinfoViewController *userinfo = [[UserinfoViewController alloc] init];
//    userinfo.userid = [NSString stringWithFormat:@"%ld",(long)model.userid];
//    userinfo.infoDic=[model mj_keyValues];
//
//
//    [self.navigationController pushViewController:userinfo animated:YES];
}


@end
